#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "au.h"

struct strmap {
	const char *str;
	uint32_t val;
};

const struct strmap strmap[] = {
	{ "ULAW", AU_ULAW },
	{ "MULAW", AU_ULAW },
	{ "U-LAW", AU_ULAW },
	{ "MU-LAW", AU_ULAW },
	{ "PCM8", AU_PCM8 },
	{ "PCM-8", AU_PCM8 },
	{ "PCM16", AU_PCM16 },
	{ "PCM-16", AU_PCM16 },
	{ "PCM24", AU_PCM24 },
	{ "PCM-24", AU_PCM24 },
	{ "PCM32", AU_PCM32 },
	{ "PCM-32", AU_PCM32 },
	{ "FLOAT", AU_FLOAT32 },
	{ "FLOAT32", AU_FLOAT32 },
	{ "FLOAT-32", AU_FLOAT32 },
	{ "DOUBLE", AU_FLOAT64 },
	{ "FLOAT64", AU_FLOAT64 },
	{ "FLOAT-64", AU_FLOAT64 },
	{ "FIXED8", AU_FIXED8 },
	{ "FIXED-8", AU_FIXED8 },
	{ "FIXED16", AU_FIXED16 },
	{ "FIXED-16", AU_FIXED16 },
	{ "FIXED24", AU_FIXED24 },
	{ "FIXED-24", AU_FIXED24 },
	{ "FIXED32", AU_FIXED32 },
	{ "FIXED-32", AU_FIXED32 },
	{ "ALAW", AU_ALAW },
	{ "A-LAW", AU_ALAW },
	{ NULL, 0 }
};

const char *
au_encstr(uint32_t val)
{
	size_t i;

	for (i = 0; strmap[i].str != NULL; i++)
		if (strmap[i].val == val)
			return (strmap[i].str);
	return (NULL);
}

size_t
au_encsize(uint32_t enc)
{

	switch (enc) {
	case AU_ULAW:
		return (1);
	case AU_PCM8:
		return (1);
	case AU_PCM16:
		return (2);
	case AU_PCM24:
		return (3);
	case AU_PCM32:
		return (4);
	case AU_FLOAT32:
		return (4);
	case AU_FLOAT64:
		return (8);
	case AU_FIXED8:
		return (1);
	case AU_FIXED16:
		return (2);
	case AU_FIXED24:
		return (3);
	case AU_FIXED32:
		return (4);
	case AU_ALAW:
		return (1);
	}
	return (0);
}

uint32_t
au_strenc(const char *str)
{
	char *p;
	size_t i;
	uint32_t r;

	assert(str != NULL);
	for (i = 0; strmap[i].str != NULL; i++)
		if (strcasecmp(strmap[i].str, str) == 0)
			return (strmap[i].val);
	r = strtoul(str, &p, 0);
	if (r <= AU_ENCMAX && p != str && *p == '\0')
		return (r);
	return (0);
}

int
au_encbswap(uint32_t enc, void *b, size_t size)
{
	size_t i;
	size_t j;
	size_t o;
	char *cb = b;
	char t;

	assert(b != NULL);
	if ((o = au_encsize(enc)) < 2)
		return (0);
	for (i = 0; i < size / o; i++)
		for (j = 0; j < o / 2; j++) {
			t = cb[i * o + j];
			cb[i * o + j] = cb[i * o + (o - j - 1)];
			cb[i * o + (o - j - 1)] = t;
		}
	return (0);
}

int
au_encnswap(uint32_t enc, void *b, size_t size)
{
	const uint32_t e = 1;

	return (((const char *)&e)[0] ? au_encbswap(enc, b, size) : 0);
}
